package top.shenluw.springdemo;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Shenluw
 * 创建日期：2019/1/21 12:09
 */
@Component
public class TestProducer {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Queue queue;
    @Autowired
    private Topic topic;

    private AtomicLong count = new AtomicLong();

    @Scheduled(fixedDelay = 5000)
    public void send() {
        jmsMessagingTemplate.convertAndSend("spring.test", "send data " + count.incrementAndGet());
    }

    @Scheduled(fixedDelay = 3200)
    public void sendWithQueue() {
        jmsMessagingTemplate.convertAndSend(queue, "send queue data " + count.incrementAndGet());
    }

    @Scheduled(fixedDelay = 3400)
    public void sendWithTopic() {
        jmsMessagingTemplate.convertAndSend(topic, "send topic data " + count.incrementAndGet());
    }

}

@Configuration
class Config {

    @Bean
    public Queue activemqQueue() {
        return new ActiveMQQueue("spring.test.queue");
    }

    @Bean
    public Topic activemqTopic() {
        return new ActiveMQTopic("spring.test.topic");
    }

    @Bean("queueFactory")
    public JmsListenerContainerFactory<?> queueFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(false);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }

    @Bean("topicFactory")
    public JmsListenerContainerFactory<?> topicFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(true);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }
}